﻿using AutoMapper;
using MediatR;
using ProduceBasicData.Api.Application.Command.Workshop;
using ProduceBasicData.Domain.FactoryModeling;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;
using Yitter.IdGenerator;
using ProduceBasicData.Api.Services;

namespace ProduceBasicData.Api.Application.Handler.Workshop
{
    /// <summary>
    /// 车间管理信息录入处理类
    /// </summary>
    public class CreateWorkshopHandler : IRequestHandler<CreateWorkshopCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<Workshopmodel> shopRepo;
        private readonly IMapper mapper;
        private readonly ICodeRuleService codeRuleService;

        public CreateWorkshopHandler(IBaseRespository<Workshopmodel> shopRepo,
            IMapper mapper,ICodeRuleService codeRuleService)
        {
            this.shopRepo = shopRepo;
            this.mapper = mapper;
            this.codeRuleService = codeRuleService;
        }

        public async Task<ApiResult<int>> Handle(CreateWorkshopCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var model=mapper.Map<Workshopmodel>(request);

            //编码
            if (string.IsNullOrEmpty(model.Workshopcode))
            {
                var code = await codeRuleService.AutoGenerateCodeAsync("ProduceBasicData.Domain.FactoryModeling.Workshopmodel");
                if (!string.IsNullOrEmpty(code))
                {
                    model.Workshopcode = code;
                }
                else
                {
                    model.Workshopcode = $"CJ{DateTime.Now:yyyyMMddHHmmss}";
                }
            }

            model.CreateName=request.CreateName;
            model.CreateTime=DateTime.Now;
            model.UserId = request.UserId;



            var r=await shopRepo.AddAsync(model);
            if (r>0)
            {
                res.Data = r;
                res.Code=ApiEnum.Success;
                res.Msg = "车间信息添加成功";
            }
            else
            {
                res.Code = ApiEnum.Failed;
                res.Msg = "车间信息添加失败";
            }
            return res;
        }
    }
}
